package com.protocolterminal.frame;

import com.protocolterminal.base.Control;
import com.protocolterminal.function.FrameFunction;

/**
 * @ClassName: BaseFrame
 * @Description: 基础376.1类
 * @author baozhijian
 * @date 2017年7月24日 下午4:30:33
 * @version V1.0
 */
public class Frame3761 {

	private String len;
	private Control control;
	private String address;
	private String data;
	private String cs;

	public String getLen() {
		return len;
	}

	public Control getControl() {
		return control;
	}

	public String getAddress() {
		return address;
	}

	public String getData() {
		return data;
	}

	public String getCs() {
		return cs;
	}

	public Frame3761(Control control, String address, String data) {

		this.control = control;
		if (address.length() == 8) {
			this.address = address + "14";
		}else{
			this.address = address;
		}
		this.data = data;

		String userdata = this.control + this.address + this.data;
		int len = userdata.length() / 2;
		this.len = Integer.toHexString((len << 2) | 0x10002).substring(1);

		FrameFunction frameFunction = new FrameFunction();
		this.cs = frameFunction.Cs(userdata);

	}

	public Frame3761(String frame) {
		FrameFunction frameFunction = new FrameFunction();

		this.len = frameFunction.Reverse(frame.substring(2, 6));
		this.control = new Control(frame.substring(12, 14));
		this.address = frameFunction.Reverse(frame.substring(14, 18)) + frameFunction.Reverse(frame.substring(18, 22))
				+ frame.substring(22, 24);

		int len = Integer.valueOf(this.len, 16) >> 2;
		this.data = frame.substring(24, 24 + 2 * (len - 6));

		this.cs = frame.substring(frame.length() - 4, frame.length() - 2);
	}

	@Override
	public String toString() {
		FrameFunction frameFunction = new FrameFunction();
		return "68" + frameFunction.Reverse(this.len) + frameFunction.Reverse(this.len) + "68" + this.control.toString()
				+ frameFunction.Reverse(this.address.substring(0, 4))
				+ frameFunction.Reverse(this.address.substring(4, 8)) + this.address.substring(8, 10) + this.data
				+ this.cs + "16";
	}

}
